﻿using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Orleans.Hosting;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace IOP.Orleans.Server
{
    /// <summary>
    /// 奥尔良服务器监控服务
    /// </summary>
    public class OrleansServerMonitorHostService : IHostedService
    {
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<OrleansServerMonitorHostService> _Logger;
        /// <summary>
        /// 主机生命周期服务
        /// </summary>
        private readonly IHostApplicationLifetime _AppLifetime;
        /// <summary>
        /// 奥尔良主机
        /// </summary>
        private ISiloHost _Silo;

        public OrleansServerMonitorHostService(ILogger<OrleansServerMonitorHostService> logger, IHostApplicationLifetime applicationLifetime, ISiloHost silo)
        {
            _Logger = logger;
            _AppLifetime = applicationLifetime;
            _Silo = silo;
        }
        /// <summary>
        /// 启动主机
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            _AppLifetime.ApplicationStarted.Register(OnStarted);
            _AppLifetime.ApplicationStopped.Register(OnStopped);
            _AppLifetime.ApplicationStopping.Register(OnStopping);
            await _Silo.StartAsync(cancellationToken);
        }
        /// <summary>
        /// 停止
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task StopAsync(CancellationToken cancellationToken)
        {
            await _Silo.StopAsync();
        }

        /// <summary>
        /// 当主机启动时
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public void OnStarted()
        {
            _Logger.LogInformation("The Orleans server has started");
        }
        /// <summary>
        /// 当主机正在停止时
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public void OnStopping()
        {
            _Logger.LogInformation("The Orleans server has begin stop");
        }
        /// <summary>
        /// 当主机完全停止时
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public void OnStopped()
        {
            _Silo.Dispose();
            _Logger.LogWarning("The Orleans server has stoped");
        }
    }
}
